package davion.study.summercloud.controller;

import davion.study.summercloud.model.FileStore;
import davion.study.summercloud.model.FileStoreStatistics;
import davion.study.summercloud.model.User;
import davion.study.summercloud.service.FileStoreService;
import davion.study.summercloud.service.UserService;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthGiteeRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: Davion
 * @date: 2020/6/3
 * @description: 登录控制器
 */
@Controller
public class LoginController {

    @Value("${gitee.client_id}")
    private String clientId;

    @Value("${gitee.client_secret}")
    private String clientSecret;

    @Value("${gitee.redirect_uri}")
    private String redirectUri;

    @Autowired
    UserService userService;

    @Autowired
    FileStoreService fileStoreService;

    private Logger logger = LoggerFactory.getLogger(LoginController.class);

    private AuthRequest getAuthRequest(){
        return new AuthGiteeRequest(AuthConfig.builder()
                .clientId(clientId)
                .clientSecret(clientSecret)
                .redirectUri(redirectUri)
                .build());
    }

    @GetMapping("/")
    public String welcome(HttpServletRequest request){
        Object user = request.getSession().getAttribute("user");
        if (user != null) {
            return "redirect:/index";
        }
        return "login";
    }

    @RequestMapping("/index")
    public String index(HttpServletRequest request, Model model){
        User user = (User) request.getSession().getAttribute("user");
        model.addAttribute("user", user);
        FileStoreStatistics statistics = fileStoreService.getCountStatistics(user.getId());
        model.addAttribute("statistics", statistics);
        request.getSession().setAttribute("statistics", statistics);
        return "u-admin/index";
    }

    @GetMapping("/login")
    public void login(HttpServletResponse response) {
        AuthRequest authRequest = getAuthRequest();
        try {
            response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
        } catch (IOException e) {
            logger.error("跳转失败！！！");
        }
    }

    @GetMapping("/callback")
    public String callback(AuthCallback callback, HttpServletResponse response, HttpServletRequest request, Model model){
        AuthRequest authRequest = getAuthRequest();
        AuthResponse<AuthUser> login = authRequest.login(callback);
        if (login.getCode() != 2000){
            logger.error(login.getMsg());
            return "登录失败" + login.getMsg();
        }
        AuthUser userData = login.getData();
        User dbUser = userService.getByUuid(userData.getUuid());
        if (dbUser == null){
            User newUser = new User();
            newUser.setUuid(userData.getUuid());
            newUser.setUsername(userData.getNickname());
            newUser.setAdmin(0);
            newUser.setImagePath(userData.getAvatar());
            newUser.setLevel(0);
            newUser.setCreateTime(System.currentTimeMillis());
            newUser.setModifyTime(newUser.getCreateTime());
            if (userService.insert(newUser)){
                dbUser = userService.getByUuid(newUser.getUuid());
                logger.info("用户注册成功，当前用户为：" + dbUser.getUsername());
                FileStore fileStore = new FileStore();
                fileStore.setUserId(dbUser.getId());
                fileStore.setCurrentSize(0);
                fileStore.setMaxSize(1048576);
                if (fileStoreService.insert(fileStore)) {
                    logger.info("仓库注册成功！！！");
                } else {
                    logger.error("仓库注册失败！！！");
                }
            } else {
                logger.error("用户注册失败！！！");
            }
        } else {
            dbUser.setUsername(userData.getNickname());
            dbUser.setImagePath(userData.getAvatar());
            dbUser.setModifyTime(System.currentTimeMillis());
            logger.info("登录成功，当前用户为：" + dbUser.getUsername());
            userService.update(dbUser);
        }
        request.getSession().setAttribute("user", dbUser);
        return "redirect:/index";
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request){
        logger.info("退出登录！！！");
        request.getSession().invalidate();
        return "redirect:/";
    }

    @RequestMapping("/testUser")
    public String testUser(HttpServletRequest request, String admin){
        System.out.println(admin);
        if (!"true".equals(admin)) {
            return "redirect:/";
        }
        User user = userService.getById(1);
        request.getSession().setAttribute("user", user);
        logger.info("测试用户登录，当前用户为：" + user.getUsername());
        return "redirect:/index";
    }
}
